package com.sinopec.pi.scalaguide

import scala.util.control.Breaks

object ControlStructure {

    private def ifStatement(): Unit = {
        // if else 语句具有返回值
        val returnCode = 0
        val success = if (returnCode == 0) {
            true
        } else {
            false
        }
    }

    private def whileStatement(): Unit = {
        //  while 循环语句
        var count: Int = 0
        while (count < 10) {
            println(s"count is ${count}")
            count += 1
        }
    }

    private def forStatement(): Unit = {
        // for 循环示例 1
        for (i <- 1 to 10) {
            println(s"i is ${i}")
        }

        // for 循环示例 2：获取下标
        val array = Array(1, 2, 3, 4, 5, 6)
        for (i <- array.indices) {
            println(s"the ${i} element is ${array(i)}")
        }

        // for 循环示例 3：双重循环
        for (i <- 1 to 3; j <- 1 to 3) {
            println(s"i is ${i}, j is ${j}")
        }

        // for 循环示例3：支持过滤器
        for (i <- array if i % 2 == 0) {
            println(s"the odd element is ${i}")
        }

        // 等价于下面的方法
        for (i <- array) {
            if (i % 2 == 0) {
                println(s"the odd element is ${i}")
            }
        }
        // 等价于下面的函数式编程
        array.filter(_ % 2 == 0).foreach(
            x => println(s"the odd element is ${x}"))
    }

    private def breakStatement(): Unit = {
        // 单循环的 break 语句
        val data = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // 核心是通过 异常 来控制
        val loop = new Breaks;
        loop.breakable {
            for (a <- data) {
                println("Value of a: " + a);
                if (a == 4) {
                    loop.break;
                }
            }
        }

        // 双重循环的 break
        val numList1 = List(1,2,3,4,5);
        val numList2 = List(11,12,13);
        val outer = new Breaks
        val inner = new Breaks
        outer.breakable {
            for( a <- numList1){
                println( "Value of outer: " + a );
                inner.breakable {
                    for( b <- numList2){
                        println( "Value of inner: " + b );
                        if( b == 12 ){
                            // break outer
                            outer.break
                        }
                    }
                } // inner breakable
            }
        } // outer breakable.
    }

    def main(args: Array[String]): Unit = {

        ifStatement()

        whileStatement()

        forStatement()

        breakStatement()

    }
}
